import store from '@/store'
import config from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import { handleUnauthorized} from "@/utils/refToken";

let timeout = 1000 * 60
const baseUrl = config.baseUrl
const request = config => {
	if (config.loading) {
		var time = setTimeout(uni.showLoading,500)
	}
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['token'] = getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	if(config.header.setType){
		config.header['Content-Type'] = config.header.setType
	}else{
		config.header['Content-Type'] = "application/json"
	}
	return new Promise((resolve, reject) => {
		const requestTask =  uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json',
			success: (response) => {
				let {
					errMsg,
					data
				} = response
				if (errMsg !== "request:ok") {
					toast('后端接口连接异常。')
					reject('后端接口连接异常')
					return
				}
				if (data.code === 10010002) {
					// 获取新的token
					return handleUnauthorized(config, resolve, reject)
				}
				const code = data.code || 200
				const msg = errorCode[code] || data.msg || errorCode['default']
				 if (code === 500) {
					toast(msg)
					reject('500')
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				resolve(data)
			},
			fail: (error) => {
				let {
					errMsg
				} = error
				if (errMsg === 'Network Error') {
					errMsg = '后端接口连接异常'
				} else if (errMsg.includes('timeout')) {
					errMsg = '系统接口请求超时'
				} else if (errMsg.includes('Request failed with status code')) {
					errMsg = '系统接口' + errMsg.substr(errMsg.length - 3) + '异常'
				}
				// 宿主中断请求 不提示
				if(errMsg !== 'request:fail abort'){
					toast(errMsg)
				}
				reject(error)
			},
			complete: () => {
				clearTimeout(time)
				if(config.loading)uni.hideLoading()
				getApp().globalData.apiList.delete(config.url)
			}
		})
		getApp().globalData.apiList.set(config.url, requestTask)
	})
}
export default request
